part of my_base_lib;

class HttpUtils {
  static Map<Object, List<http.Client>> clients = {};

  static cancel(Object tag) {
    try {
      List<http.Client>? list = clients[tag];
      if (list != null) {
        list.forEach((element) {
          try {
            element.close();
          } catch (ee) {}
        });
      }
      clients.remove(tag);
    } catch (e) {}
  }

  static Future<File?> doDownload(
      String url, String fileName, Object tag) async {
    http.Client client = http.Client();
    (clients[tag] ??= []).add(client);
    http.Response response = await client.get(Uri.parse(url));
    if (response.statusCode == 200) {
      String path = FileUtils.getDefaultPathByFileName(fileName);
      File file = File(path);
      if (file.existsSync()) {
        file.deleteSync();
      }
      file.writeAsBytesSync(response.bodyBytes);
      return file;
    } else {
      return null;
    }
  }

  static Future<String?> doUpload(String url,String fileName, String filePath,
      {String requestType = "POST", Map<String, String>? bodyParams,Map<String, String>? headersMap}) async {
    var request = http.MultipartRequest(requestType, Uri.parse(url));
    var file = await http.MultipartFile.fromPath(fileName, filePath); //文件路径
    String sp = "";
    request.files.add(file);
    if(bodyParams!=null){
      request.fields.addAll(bodyParams);
    }
    if(headersMap!=null){
      request.headers.addAll(headersMap);
    }
    /*if (!CommonUtils.isEmpty(UserUtils.getToken())) {
      request.headers["token"] = "Bearer ${UserUtils.getToken()}";
    }*/


    print("\n*******************文件发起上传******************************");
    var response = await request.send();
    sp = await response.stream.bytesToString();
    // 获取响应内容
    print('Response: $sp');
    print("\n*****************************************************");
    CommonUtils.printString(
        "\n接口响应：\nurl = $url\nstatusCode = ${response.statusCode} \nresponse.body = $sp\n");
    return sp;
  }

  static Future<NetResponse?> doPost(String url, Object tag,
      {Map<String, String>? headersMap,
      Map<String, Object>? bodyParams,
        String? fileName,Uint8List? uint8list,

      String contentType = "application/x-www-form-urlencoded",
      Encoding encoding = const Utf8Codec()}) async {
    //设置header
    headersMap ??= {};
    headersMap["content-type"] = contentType;
    /*if (!CommonUtils.isEmpty(UserUtils.getToken())) {
      headersMap["token"] = "Bearer ${UserUtils.getToken()}";
    }*/
    //设置请求body

    bodyParams ??= {};

    print("\n*****************************************************");
    CommonUtils.printString("\n发起请求：Post"
        "\nurl = $url"
        "\nheader = $headersMap"
        "\nbody = $bodyParams\n");
    print("*****************************************************\n");

    http.Client client = http.Client();
    (clients[tag] ??= []).add(client);


    NetResponse? netResponse;
    await client
        ?.post(Uri.parse(url),
            headers: headersMap, body: bodyParams, encoding: encoding)
        .then((http.Response response) {
      print("\n*****************************************************");
      CommonUtils.printString(
          "\n接口响应：\nurl = $url\nstatusCode = ${response.statusCode} "
          " \nheader = ${response.headers}"
          " \nresponse.body = ${response.body}\n");
      try {
        client?.close();
        clients.remove(tag);
      } catch (e) {}
      netResponse = NetResponse()
        ..statusCode = response.statusCode
        ..headers = response.headers
        ..body = response.body
        ..bodyBytes = response.bodyBytes;
    }).catchError((error, stackTrace) {
      print('error:$error');
      print('Stack trace:$stackTrace');
      print("*****************************************************\n");
      try {
        client?.close();
        clients.remove(tag);
      } catch (e) {}
    });
    return netResponse;
  }

  static Future<String> doGet(String url,
      {Map<String, String>? headersMap,
      Map<String, Object>? bodyParams}) async {
    String sp = "";

    headersMap ??= {};
    bodyParams ??= {};

    /*if (!CommonUtils.isEmpty(UserUtils.getToken())) {
      headersMap["token"] = "Bearer ${UserUtils.getToken()}";
    }*/

    bool firstParam = true;
    bodyParams.forEach((key, value) {
      if (firstParam) {
        url += "?";
        firstParam = false;
      } else {
        url += "&";
      }
      url += "$key=$value";
    });

    await http
        .get(Uri.parse(url), headers: headersMap)
        .then((http.Response response) {
      sp = response.body;

      print("\n*****************************************************");
      CommonUtils.printString("\n发起请求：Get"
          "\nurl = $url"
          "\nheader = $headersMap");
      print("*****************************************************\n");

      print("\n*****************************************************");
      CommonUtils.printString(
          "\n接口响应：\nurl = $url\nstatusCode = ${response.statusCode} \nresponse.body = ${response.body}\n");
    }).catchError((error) {
      print('error');
      print("*****************************************************\n");
    });
    return sp;
  }
}
